package com.von.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.von.entity.Token;
import com.von.entity.User;
import com.von.enums.UserEnum;
import com.von.mapper.UserMapper;
import com.von.param.UserParam;
import com.von.result.R;
import com.von.service.ITokenService;
import com.von.service.IUserService;
import com.von.util.Aes;
import com.von.util.RedisUtil;
import com.von.util.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Optional;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author xiaosai
 * @since 2021-06-17
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Resource
    private ITokenService iTokenService;
    @Resource
    private RedisUtil redisUtil;
    @Resource
    private IUserService userService;

    @Override
    public R<String> login(UserParam param) {
        if(StrUtil.isEmpty(param.getUserPassword())){
            return R.failed(UserEnum.PASSWORD_ERROR.getMsg());
        }
        if(StrUtil.isNotEmpty(param.getUserName())){
            User user = lambdaQuery().eq(User::getUserName, param.getUserName()).eq(User::getUserPassword, Aes.encryptAES(param.getUserPassword())).one();
            if(user!=null){
                //清空上一次的
                redisUtil.dimDel(TokenUtils.TOKEN_PREFIX+user.getId());
                String token = TokenUtils.build(user.getId());
                redisUtil.set(token,user,30*60);
                return R.ok(token);
            }
            return R.failed(UserEnum.ACCOUNT_PASSWORD_ERROR.getMsg());
        }
        return R.failed(UserEnum.LOGIN_FAILED.getMsg());
    }

    @Override
    public R<String> logout(String token) {
        if(StrUtil.isEmpty(token)){
            return R.failed(UserEnum.LOGOUT_FAILED.getMsg());
        }
        redisUtil.del(token);
        return R.failed(UserEnum.LOGOUT_OK.getMsg());
    }

    @Override
    public R<String> register(User user) {
        Integer count = userService.lambdaQuery().eq(User::getUserName, user.getUserName()).count();
        if(count>0){
            return R.failed(UserEnum.ACCOUNT_IS_EXIST.getMsg());
        }
        //对密码进行加密处理
        String aes = Aes.encryptAES(user.getUserPassword());
        if(StrUtil.isEmpty(aes)){
            return R.failed(UserEnum.REGISTER_FAILED.getMsg());
        }
        user.setUserPassword(aes);
        userService.save(user);
        return R.ok(UserEnum.REGISTER_OK.getMsg());
    }
}
